<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>双向链表</title>
</head>
<body>
<pre>
    将M个人围成一圈，并且将第N个踢出，计算哪两个人会留在最后
</pre>
<script>
    var Node= function (elm) {
        this.elm=elm;
        this.prev=null;
        this.next=null;
    };


    function List(){
        this.head=new Node('head');
        this.head.next=this.head;
    }
    List.prototype={
        constructor:List,
        each: function (cb) {
            var curr=this.head;
            do{
                cb(curr);
            }while(curr=curr.next);
        },
        find: function (item) {
            var curr=this.head;
            do{
                if(curr.elm==item){
                    return curr;
                }
            }while(curr=curr.next);
            return null;
        },
        findLast: function () {
            var curr=this.head;
            while(curr.next!=null){
                curr=curr.next;
            }
            return curr;
        },
        display: function () {
            console.info('display:');
            return console.log(this);
        },
        insert: function (newElm,target) {
            var curr=this.find(target),newNode;
            if(!curr)return false;
            newNode=new Node(newElm);
            newNode.next=curr.next;
            newNode.prev=curr;
            newNode.next=this.head;
            curr.next=newNode;
            curr.prev=newNode;
            this[newElm]=newNode;
            return true;
        },

        prev: function (elm) {
            var curr=this.head;
            do{
                if(curr.next&&curr.next.elm==elm){
                    return curr;
                }
            }while(curr=curr.next);
            return null;
        },
        remove: function (elm) {
            var del=this.find(elm);
            if(!del)return false;
            del.prev.next=del.next;
            del.next.prev=del.prev;
            delete this[elm];
            return true;
        }
    };

    function T(m,n){
        var list=new List(),curr='head',newNode,newName;
        for(var i=1;i<=m;i++){
            newName=String(i);
            newNode=new Node(newName);
            list.insert(newName,curr);
            curr=String(i);
        }
        list.remove('head');

        console.log(list);
    }

    T(10,2);
</script>
</body>
</html>